package com.buildings.util;

import android.Manifest;


import com.buildings.base.BaseActivity;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class HYPermissionUtil {

    private static Map<String, Boolean> grantedMap = new HashMap<>();

    public static void checkPermissions(BaseActivity activity, PermissionResult result) {
        grantedMap.clear();
        new RxPermissions(activity)
                .requestEach(
                        Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_NETWORK_STATE,
                        Manifest.permission.ACCESS_COARSE_LOCATION)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Permission>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Permission permission) {
                        if (permission == null || grantedMap == null) {
                            return;
                        }
                        grantedMap.put(permission.name, permission.granted);
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {
                        result.result(hasGranted());
                    }
                });
    }


    private static boolean hasGranted() {
        if (grantedMap == null || grantedMap.size() == 0) {
            return false;
        }
        for (Boolean granted : grantedMap.values()) {
            if (!granted) {
                return false;
            }
        }
        return true;
    }

    public interface PermissionResult {
        void result(boolean granted);
    }
}
